package com.lvmama.task.job.monitor;

import com.lvmama.task.common.utils.TaskUtil;
import com.lvmama.task.job.common.TaskJobParameters;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;


/**
 * Created by troy on 2016/6/27.
 * kouhongyu@163.com
 */
public class TaskMonitor implements Runnable {

    private static Log LOG = LogFactory.getLog(TaskMonitor.class);

    private ServerSocket serverSocket;
    private Socket socket;
    private PrintWriter out;
    private String portStr;

    private TaskMonitor() {

    }

    public TaskMonitor(String portStr) {
        this.portStr = portStr;
    }

    public void run() {
        try {
            int port = Integer.parseInt(portStr);
            serverSocket = new ServerSocket(port);

            while (true) {
                socket = serverSocket.accept();
                out = new PrintWriter(socket.getOutputStream(), true);

                JSONObject jsonMap = new JSONObject();

                jsonMap.put("hostName", TaskUtil.hostName());
                jsonMap.put("owner", TaskJobParameters.TASK_JOB_OWNER);
                jsonMap.put("jobNode", TaskJobParameters.TASK_JOB_NODE);
                jsonMap.put("monitorPort", TaskJobParameters.TASK_MONITOR_PORT);
                jsonMap.put("time", DateFormatUtils.format(new Date(), DateFormatUtils.ISO_DATETIME_FORMAT.getPattern()));


                out.print(jsonMap);

                out.close();
                socket.close();
            }
        } catch (IOException e) {
            LOG.error(e);
        }
    }
}
